package main

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/inner/uuid"
	"go.uber.org/zap"
	"mxshop_api/goods-web/global"
	"mxshop_api/goods-web/initialize"
	"mxshop_api/goods-web/utils"
	"mxshop_api/goods-web/utils/register/consul"
	"os"
	"os/signal"
	"syscall"
)

func main() {

	/**
	1.修改复制的goods-web项目
	2.修改nacos里面的配置
	3.
	*/

	//初始化logger
	initialize.InitLogger()
	//初始化配置文件
	initialize.InitConfig()
	//初始化router
	routers := initialize.Routers()
	//初始化错误翻译
	if err := initialize.InitTrans("zh"); err != nil {
		panic(err)
	}
	initialize.InitSrvConn()

	////注册验证器
	//if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
	//	_ = v.RegisterValidation("mobile", myvalidator.ValidatorMobile)
	//	_ = v.RegisterTranslation("mobile", global.Trans, func(ut ut.Translator) error {
	//		return ut.Add("mobile", "{0} 非法的手机号码！", true)
	//	}, func(ut ut.Translator, fe validator.FieldError) string {
	//		t, _ := ut.T("mobile", fe.Field())
	//		return t
	//	})
	//}
	if !global.ServerConfig.MxshopDebug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.ServerConfig.Port = port
		}
	}

	zap.S().Debugf("启动服务器，端口:%d", global.ServerConfig.Port)

	//注册consul 使用uuid.NewV4
	registerClient := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	ServerId, err := uuid.NewV4()
	if err != nil {
		zap.S().Panic("uuid获取失败:", err.Error())
	}
	err = registerClient.Register(global.ServerConfig.Host, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, ServerId.String())
	if err != nil {
		zap.S().Panic("服务注册失败:", err.Error())
	}

	go func() {
		err = routers.Run(fmt.Sprintf(":%d", global.ServerConfig.Port))
		if err != nil {
			zap.S().Panic("启动失败:", err.Error())
		}
	}()

	//优雅退出
	var quit = make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	err = registerClient.DeRegister(ServerId.String())
	if err != nil {
		zap.S().Panic("注销失败:", err.Error())
	} else {
		zap.S().Panic("注销成功")
	}
}
